package cn.regexp.job.executor.jobHandler;

import cn.regexp.domain.ShopBanner;
import cn.regexp.service.IBannerService;
import cn.regexp.utils.RedisKeys;
import com.alibaba.fastjson.JSON;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class BannerXxlJob {
    private static Logger logger = LoggerFactory.getLogger(CanteenXxlJob.class);
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IBannerService bannerService;

    @XxlJob("cacheBannerJobHandler")
    public void cacheBannerJobHandler() throws Exception {
        XxlJobHelper.log("同步轮播图到Redis --> start");
        String key = RedisKeys.BANNER_INFO.join();
        // 如果存在该 key，则删除
        if (Objects.equals(redisTemplate.hasKey(key),Boolean.TRUE)) {
            redisTemplate.delete(key);
        }
        // 查询轮播图
        List<ShopBanner> bannerList = bannerService.queryBanner();
        redisTemplate.opsForValue().set(key, JSON.toJSONString(bannerList),
                RedisKeys.BANNER_INFO.getTime(), TimeUnit.DAYS);
        XxlJobHelper.log("同步轮播图到Redis --> end");
    }
}
